<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? '编辑教研活动' : '添加教研活动'"
    :width="520"
    @ok="handleSubmit"
    @register="registerModal"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from "vue";
  import { teachingRecordFormSchema } from "../task.data";
  import { useMessage } from "/@/hooks/web/useMessage";
  import { BasicForm, useForm } from "/@/components/Form";
  import { BasicModal, useModalInner } from "/@/components/Modal";
  import { defaultModalFormSettings } from "/@/hooks/core/useDefault";
  import { saveTeachingRecordApi, updateTeachingRecordApi } from "/@/api/core/teachingRecord";
  import { OperTypeEnum } from "/@/enums/typeEnum";

  const isUpdate = ref(false);

  const [registerModal, { closeModal, changeLoading, changeOkLoading }] = useModalInner(
    ({ data, operType }) => {
      if (operType === OperTypeEnum.UPDATE) {
        isUpdate.value = true;
        data.docLink = data.docLink === "" ? [] : [data.docLink];
        setFieldsValue({ ...data });
      } else if (operType === OperTypeEnum.SAVE) {
        isUpdate.value = false;
        resetFields();
      }
    },
  );

  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelWidth: 80,
    schemas: teachingRecordFormSchema,
    ...defaultModalFormSettings,
  });

  const { createMessage } = useMessage();

  async function handleSubmit() {
    try {
      const value = await validate();
      changeLoading(true);
      changeOkLoading(true);
      if (unref(isUpdate)) {
        await updateTeachingRecordApi(value);
        createMessage.success("更新课堂教学记录成功");
      } else {
        await saveTeachingRecordApi(value);
        createMessage.success("添加课堂教学记录成功");
        return;
      }
      closeModal();
    } finally {
      changeLoading(false);
      changeOkLoading(false);
    }
  }
</script>
